package com.everflourish.yeah100.act.questionlib;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.everflourish.yeah100.R;
import com.everflourish.yeah100.act.base.BaseActivity;
import com.everflourish.yeah100.adapter.QuestionTagsAdapter;
import com.everflourish.yeah100.entity.question.Question;
import com.everflourish.yeah100.entity.question.QuestionTag;
import com.everflourish.yeah100.entity.question.QuestionTagModel;
import com.everflourish.yeah100.http.QuestionRequest;
import com.everflourish.yeah100.ui.animator.CustomItemAnimator;
import com.everflourish.yeah100.ui.dialog.LoadDialog;
import com.everflourish.yeah100.utils.IntentUtil;
import com.everflourish.yeah100.utils.KeyBoardUtils;
import com.everflourish.yeah100.utils.LogUtil;
import com.everflourish.yeah100.utils.MyToast;
import com.everflourish.yeah100.utils.ResourcesUtil;
import com.everflourish.yeah100.utils.StringUtil;
import com.everflourish.yeah100.utils.constant.Constant;
import com.everflourish.yeah100.utils.constant.ResultCode;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * 作者：Created by liqisi on 2016/7/26.
 * 时间：2016/7/26
 */
public class QuestionFavoriteActivity extends BaseActivity {

    private Toolbar mToolBar;
    private RecyclerView mQuestionTagRv;
    public EditText mQuestionTagTv;
    public TextInputLayout mQuestionTagTil;
    public TextView mQuestionTagRuleTv;
    public QuestionRequest mRequest;
    private Question mQuestion;
    private LoadDialog mLoadDialog;
    private String mExaminationId;
    private QuestionTagsAdapter mAdapter;
    private List<QuestionTagModel> mList;
    private boolean isUpdate;

    /**
     * 每次加载10条
     */
    private int mSelectCount = 9;
    /**
     * 加载的位置
     */
    private int mStartIndex = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_question_favorite);
        initData();
        initView();
        configView();
    }

    private void initData() {
        mList = new ArrayList<QuestionTagModel>();
        mRequest = QuestionRequest.getInstance();
        mQuestion = (Question) getIntent().getSerializableExtra(IntentUtil.QUESTION_UPDATE);
        mExaminationId = getIntent().getStringExtra(IntentUtil.EXAMINATION_ID);
        mAdapter = new QuestionTagsAdapter(mContext, this, mList);
    }

    private void initView() {
        mQuestionTagTv = (EditText) findViewById(R.id.question_tag_et);
        mQuestionTagTil = (TextInputLayout) findViewById(R.id.question_tag_til);
        mQuestionTagRuleTv = (TextView) findViewById(R.id.question_tag_rule_tv);

        mQuestionTagRv = (RecyclerView) findViewById(R.id.question_tag_list);
        mToolBar = (Toolbar) findViewById(R.id.toolbar_question_tag);
        mToolBar.setTitle("添加标签");
        setSupportActionBar(mToolBar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    private void configView() {
        mToolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishActivity();
            }
        });
        mToolBar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.question_tag_favorite_summit:
                        String tagNameStr = mQuestionTagTv.getText().toString().trim();
                        if (tagNameStr.equals("")) {
                            mQuestionTagTil.setError("请输入标签");
                        } else {
                            mQuestionTagTil.setErrorEnabled(false);
                            mQuestionTagTil.setError(null);
                            String[] tagNameArray = tagNameStr.split(" ");
                            List<String> tagNames = new ArrayList<String>();
                            for (int i = 0; i < tagNameArray.length; i++) {
                                tagNames.add(tagNameArray[i]);
                                if (!StringUtil.is9Str(tagNameArray[i])) {
                                    mQuestionTagRuleTv.setTextColor(ResourcesUtil.getColor(mContext, R.color.error));
                                    return false;
                                }
                            }
                            List<String> questionIds = new ArrayList<String>();
                            questionIds.add(mQuestion.getQuestionId());
                            favoriteQuestionRequest(tagNames, questionIds);
                        }
                        break;
                }
                return true;
            }
        });
        mQuestionTagRv.setLayoutManager(new LinearLayoutManager(this));
        mQuestionTagRv.setItemAnimator(new CustomItemAnimator());
        mQuestionTagRv.setAdapter(mAdapter);
        getQuestionTagListRequest(mStartIndex, mSelectCount, null);
    }

    /**
     * 老师收藏题目请求
     *
     * @param tagNames
     * @param questionIds
     */
    private void favoriteQuestionRequest(List<String> tagNames, List<String> questionIds) {
        mLoadDialog = LoadDialog.show(mContext, null, "收藏中...", mQueue);
        JsonObjectRequest request = mRequest.favoriteQuestionRequest(questionIds, tagNames,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        favoriteQuestionListener(response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mRequest.disposeError(mContext, mLoadDialog, error, "收藏题目失败");
                    }
                });
        mQueue.add(request);
    }

    /**
     * 获取标签列表请求
     *
     * @param startIndex
     * @param selectCount
     * @param tagName
     */
    private void getQuestionTagListRequest(int startIndex, int selectCount, String tagName) {
        mLoadDialog = LoadDialog.show(mContext, null, "获取标签...", mQueue);
        JsonObjectRequest request = mRequest.getQuestionTagListRequest(startIndex, selectCount, tagName,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        questionTagListListener(response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mRequest.disposeError(mContext, mLoadDialog, error, "获取标签失败");
                    }
                });
        mQueue.add(request);
    }

    /**
     * 老师收藏题目监听
     *
     * @param response
     */
    private void favoriteQuestionListener(JSONObject response) {
        try {
            String resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                isUpdate = true;
                finishActivity();
            } else if (resultCode.equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.questionlib_09181_000001E);
            } else if (resultCode.equals(ResultCode.result_300005E.resultCode)) {
                MyToast.showShort(mContext, R.string.questionlib_09182_300005E);
            } else if (resultCode.equals(ResultCode.result_300025E.resultCode)) {
                MyToast.showShort(mContext, R.string.questionlib_09183_300025E);
            } else if (resultCode.equals(ResultCode.result_300028E.resultCode)) {
                MyToast.showShort(mContext, R.string.questionlib_09184_300028E);
            } else if (resultCode.equals(ResultCode.result_system_exception_999999E)) {
                MyToast.showShort(mContext, R.string.questionlib_091899_999999E);
            } else {
                MyToast.showShort(mContext, "收藏题目失败");
            }
        } catch (Exception e) {
            LogUtil.e("Json异常", e);
            MyToast.showShort(mContext, "收藏题目失败");
        } finally {
            LoadDialog.dismiss(mLoadDialog);
        }
    }

    /**
     * 获取题目标签监听
     *
     * @param response
     */
    private void questionTagListListener(JSONObject response) {
        int totalCount = 0;
        try {
            String resultCode = response.getString(Constant.RESULT_CODE);
            totalCount = response.getInt(Constant.TOTALCOUNT);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                JSONArray jsonArray = response
                        .getJSONArray(Constant.QUESTIONTAGS);
                Gson gson = new Gson();
                Type type = new TypeToken<List<QuestionTag>>() {
                }.getType();
                List<QuestionTag> questionTags = gson.fromJson(
                        jsonArray.toString(), type);
                setQuestionTagList(questionTags);
            } else if (resultCode.equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.questionlib_09171_000001E);
            } else if (resultCode.equals(ResultCode.result_300026E.resultCode)) {
                MyToast.showShort(mContext, R.string.questionlib_09174_300026E);
            } else if (resultCode.equals(ResultCode.result_system_exception_999999E)) {
                MyToast.showShort(mContext, R.string.questionlib_091799_999999E);
            } else {
                MyToast.showShort(mContext, "获取标签失败");
            }
        } catch (Exception e) {
            LogUtil.e("Json异常", e);
            MyToast.showShort(mContext, "获取标签失败");
        } finally {
            KeyBoardUtils.closeKeybord(mQuestionTagTv, mContext);
            LoadDialog.dismiss(mLoadDialog);
        }
    }

    /**
     * 设置标签列表list
     *
     * @param list
     */
    private void setQuestionTagList(List<QuestionTag> list) {
        for (QuestionTag questionTag : list) {
            QuestionTagModel questionTagModel = new QuestionTagModel();
            questionTagModel.setQuestionTag(questionTag);
            questionTagModel.setIsChecked(false);
            mList.add(questionTagModel);
        }
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finishActivity();
            return true;
        } else {
            return super.onKeyUp(keyCode, event);
        }
    }

    private void finishActivity() {
        Intent resultIntent = getIntent();
        resultIntent.putExtra(IntentUtil.QUESTION_IS_UPDATE, isUpdate);
        this.setResult(RESULT_OK, resultIntent);
        IntentUtil.finishActivity(QuestionFavoriteActivity.this);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_question_tag, menu);
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mQueue.stop();
    }
}